<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Article;
use Illuminate\Support\Facades\DB;

use BaseController;

class ArticleController extends Controller
{
    public function index()
    {
        return Article::all();
    }

    public function show(Article $article)
    {
        return $article;
    }

    public function store(Request $request)
    {
        $article = Article::create($request->all());

        return response()->json($article, 201);
    }

    public function update(Request $request, Article $article)
    {
        $article->update($request->all());

        return response()->json($article, 200);
    }

    public function delete(Article $article)
    {
        $article->delete();

        return response()->json(null, 204);
    }

    public function screenTree()
    {
        $screen = DB::table('screen')
            // ->select(DB::raw('count(*) as user_count, status'))
            ->where('delete', '<>', 1)
            ->orderBy('id')
            ->get()->toArray();
        $screen = $this->objectToArray($screen);
        
        $tree = ['id'=>0, 'text'=>'所有'];
        $this->cyclic($tree, $screen,"nodes");
        // print_r($tree);exit();
        return response()->json($tree, 200);
    }

    /**
     * 对象转换数组
     *
     * @param $e StdClass对象实例
     * @return array|void
     */
    public function objectToArray($e)
    {
        $e = (array)$e;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'resource') return;
            if (gettype($v) == 'object' || gettype($v) == 'array')
                $e[$k] = (array)$this->objectToArray($v);
        }
        return $e;
    }

    protected function cyclic(&$first, $array, $next_level = "node")
    {
        //追加子目录
        foreach ($array as $k => $v) {
            if ($v['pid'] == $first['id']) {
                $first[$next_level][] = $v;
                unset($array[$k]);
            }
        }
        //递归调用的条件
        if (isset($first[$next_level]) && count($array) > 0) {
            foreach ($first[$next_level] as $k2 => $v2) {
                $this->cyclic($first[$next_level][$k2], $array, $next_level);
            }
        }
    }
}